#RGB颜色空间中的图像分割
from skimage import data
from matplotlib import pyplot as plt
import math
import numpy as np
image = data.coffee()
r = image[:,:,0]
g = image[:,:,1]
b = image[:,:,2]
#RGB颜色空间中的分割
#选择样本区域
r1 = r[128:255,85:169]
#计算改区域中的彩色点的平均向量a的红色分量
r1_u = np.mean(r1)
#计算样本点红色分量的标准差
r1_d = 0.0
for i in  range(r1.shape[0]):
    for j in range(r1.shape[1]):
        r1_d = r1_d+(r1[i,j]-r1_u)*(r1[i,j]-r1_u)
r1_d = math.sqrt(r1_d/r1.shape[0]/r1.shape[1])
#寻找符合条件的点，r2位红色分割图像
r2 = np.zeros(r.shape,dtype='uint8')
for i in  range(r.shape[0]):
    for j in range(r.shape[1]):
        if r[i,j]>=(r1_u-1.25*r1_d) and r[i,j]<=(r1_u+1.25*r1_d):
            r2[i,j] = 1
#image2为根据红色分割后的RGB图像
image2 = np.zeros(image.shape,dtype='uint8')
for i in  range(r.shape[0]):
    for j in range(r.shape[1]):
        if r2[i,j] == 1:
            image2[i,j,:] = image[i,j,:]
#显示结果
plt.figure()
plt.axis('off')
plt.imshow(image) #显示原始RGB图像(彩色图像)
plt.figure()
plt.axis('off')
plt.imshow(r,cmap = 'gray') #显示R分量图像
plt.figure()
plt.axis('off')
plt.imshow(g,cmap = 'gray') #显示G分量图像
plt.figure()
plt.axis('off')
plt.imshow(b,cmap = 'gray') #显示B分量图像
plt.figure()
plt.axis('off')
plt.imshow(r2,cmap = 'gray') #显示红色分割图像
plt.figure()
plt.axis('off')
plt.imshow(image2) #显示分割后的RGB图像